//
//  com_conversationViewController.m
//  百车易车险
//
//  Created bychenxu on 14-8-29.
//  Copyright (c) 2014年 chenxu. All rights reserved.
//

#define kTagActionResendMessage 1005
#define kTagActionDeleteMessage 1006
#define kCellIdentifier_Message @"MessageCell"
#define kCellIdentifier_MessageMedia @"MessageMediaCell"

#import "com_conversationViewController.h"
#import "ODRefreshControl.h"
#import "NetAPIManager.h"
#import "NetBaiduManager.h"
#import "MessageCell.h"
#import "PriceView.h"
#import "PayViewController.h"
#import "carViewController.h"
#import "Insurances.h"
//#import "QBImagePickerController.h"
//#import "Helper.h"

@interface com_conversationViewController ()
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) ODRefreshControl *refreshControl;
@property (nonatomic, strong) UIMessageInputView *myMsgInputView;
@property (nonatomic, assign) CGFloat preContentHeight;
@property (nonatomic, strong) PrivateMessage *messageToResendOrDelete;
@property (nonatomic, strong) PriceView *priceView;
@property (nonatomic, strong) Insurances* ins;


@end

@implementation com_conversationViewController

#pragma mark viewDelegate
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //初始化消息列表
    _myOrder.msgs =[PrivateMessages priMsgsWithOrder:_myOrder.Orderid];
    _myOrder.badge = @"";
    _myPriMsgs = _myOrder.msgs;
    
    //读取该订单的百度id
    [_myOrder company_setBaiduid];
    
    //监听新消息
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receivemsg:) name:@"newmsg" object:nil];
    
    //读存档
    [self loadFromArchiver];
    
    
    
}

//点击下拉菜单按钮
- (void)showpriceview{
    if (!_priceView.isshow) {
        [_myMsgInputView prepareToDismiss];
    }
    else {
        [_myMsgInputView prepareToShow];
        [_myMsgInputView becomeFirstResponder];
    }
    [_priceView showOrDismiss];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (_myMsgInputView) {
        [_myMsgInputView prepareToDismiss];
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //    键盘
    if (_myMsgInputView) {
        if (!_priceView.isshow) {
            [_myMsgInputView prepareToShow];
        }
    }
    [self.myTableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"pay"]) {
        PayViewController* vc = segue.destinationViewController;
        vc.myorder = _myOrder;
    }
    else if ([segue.identifier isEqualToString:@"carinfo"]){
        carViewController* vc = segue.destinationViewController;
        vc.myOrder = _myOrder;
        
    }
}

- (void)loadView{
    [super loadView];
    CGRect frame = [UIView frameWithOutNav];
    self.view = [[UIView alloc] initWithFrame:frame];
    self.title = @"报价结果";
    //    添加myTableView
    _myTableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.backgroundColor = kColorTableBG;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableView registerClass:[MessageCell class] forCellReuseIdentifier:kCellIdentifier_Message];
        [tableView registerClass:[MessageCell class] forCellReuseIdentifier:kCellIdentifier_MessageMedia];
        [self.view addSubview:tableView];
        tableView;
    });
    
   // 下拉菜单
    //初始化priceView
    _priceView = [[PriceView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height-63) andOrder:_myOrder send:^(NSArray *insarr) {
    } selectcar:^{
        [self performSegueWithIdentifier:@"carinfo" sender:self];
    }];
    
    [self.view addSubview:_priceView];
    //下拉菜单按钮
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(showpriceview)];
    self.navigationItem.rightBarButtonItem = rightItem;
    [rightItem setImage:[UIImage imageNamed:@"下拉"]];
    
    
    
    
    _myMsgInputView = [UIMessageInputView messageInputViewWithType:UIMessageInputViewTypeSimple placeHolder:@"请输入私信内容"];
    _myMsgInputView.isAlwaysShow = YES;
    _myMsgInputView.delegate = self;
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0,CGRectGetHeight(_myMsgInputView.frame), 0.0);
    self.myTableView.contentInset = contentInsets;
    self.myTableView.scrollIndicatorInsets = contentInsets;
}

#pragma mark ReceiveMsg
- (void)receivemsg:(NSNotification*)notify{
    NSDictionary *msg = [notify valueForKey:@"object"];
    NSString *orderid = [msg valueForKeyPath:@"orderid"];
    if ([_myOrder.Orderid isEqualToString:orderid]) {
        _myOrder.badge =  [[NSString alloc]initWithFormat:@"%d",[_myOrder.badge intValue]+1];
        NSLog(@"\n收到新消息");
        NSString* talk = [msg valueForKeyPath:@"aps.alert"];
        talk = [talk stringByReplacingOccurrencesOfString:@"&n" withString:@" "];
        PrivateMessage* newmsg = [PrivateMessage privateMessageWithObj:talk andSender:opposite andusername:_myOrder.Username];
        [_myPriMsgs receiveNewMessage:newmsg];
        [_myTableView reloadData];
        
        [self scrollToBottomAnimated:YES];
        //存档
        [self saveToArchiver];
        //存到服务器
        [[NetAPIManager sharedManager]update_talk:[self toTalkParams:talk] andBlock:^(id data, NSError *error) {
            
        }];
    }
}

/*!
 *  @brief  参数化消息
 *  @param talk 消息string
 *  @return <#return value description#>
 */
- (NSDictionary* )toTalkParams:(NSString*)talk{
    return @{
             @"Orderid" : _myOrder.Orderid,
             @"Talk"    : talk,
             @"Flag"    : @"company"
             };
}

/*!
 *  @brief  持久化数据
 */
- (void)saveToArchiver{
    NSString* filename = [self filePath:_myOrder.Orderid];
    filename = [filename stringByAppendingString:@"_company"];
    NSMutableData* data = [NSMutableData data];
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:_myPriMsgs forKey:_myOrder.Orderid];
    [archiver finishEncoding];
    [data writeToFile:filename atomically:YES];
}

/*!
 *  @brief  读取数据
 */
- (void)loadFromArchiver{
    NSString* filename = [self filePath:_myOrder.Orderid];
    filename = [filename stringByAppendingString:@"_company"];
    NSMutableData* data = [NSMutableData dataWithContentsOfFile:filename];
    if ([data length] > 0) {
        NSLog(@"第一次加载");
        NSKeyedUnarchiver* unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
        _myPriMsgs = [unArchiver decodeObjectForKey:_myOrder.Orderid];
    }
}

#pragma mark UIMessageInputViewDelegate
- (void)messageInputView:(UIMessageInputView *)inputView sendText:(NSString *)text{
    [self sendPrivateMessage:text];
    
}

- (void)messageInputView:(UIMessageInputView *)inputView sendBigEmotion:(NSString *)emotionName{
    [self sendPrivateMessage:emotionName];
}

- (void)messageInputView:(UIMessageInputView *)inputView addIndexClicked:(NSInteger)index{
}

- (void)messageInputView:(UIMessageInputView *)inputView heightToBottomChenged:(CGFloat)heightToBottom{
    [UIView animateWithDuration:0.25 delay:0.0f options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        UIEdgeInsets contentInsets= UIEdgeInsetsMake(0.0, 0.0, heightToBottom, 0.0);;
        self.myTableView.contentInset = contentInsets;
        self.myTableView.scrollIndicatorInsets = contentInsets;
        [self scrollToBottomAnimated:NO];//刚加载页面滚到底部
    } completion:nil];
}

#pragma mark refresh


#pragma mark Table M

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger row = 0;
    if (_myPriMsgs.list) {
        row = [_myPriMsgs.list count];
    }
    return row;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageCell *cell;
    NSUInteger curIndex = ([_myPriMsgs.list count] -1) - indexPath.row;
    PrivateMessage *curMsg = [_myPriMsgs.list objectAtIndex:curIndex];
    
    cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Message forIndexPath:indexPath];

    if (curIndex +1 < _myPriMsgs.list.count) {
        cell.prePriMsg = [_myPriMsgs.list objectAtIndex:curIndex+1];
    }else{
        cell.prePriMsg = nil;
    }
    cell.curPriMsg = curMsg;
    
    //按了头像
    cell.tapUserIconBlock = ^(User *sender){
        
    };
    ESWeakSelf;
    
    //重新发送消息
    cell.resendMessageBlock = ^(PrivateMessage *curMessage){
        ESStrongSelf;
        
        [_myOrder company_setBaiduid];//重新读取百度id

        _self.messageToResendOrDelete = curMessage;
        [_self.myMsgInputView isAndResignFirstResponder];
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"重新发送" delegate:_self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"发送", nil];
        actionSheet.tag = kTagActionResendMessage;
        [actionSheet showInView:kKeyWindow];
    };
    
    
    cell.refreshMessageMediaCCellBlock = ^(CGFloat diff){
        ESStrongSelf;
        static int count = 0;
        NSLog(@"\ncount : ----------------%d", count++);
        [_self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [_self.myTableView setContentOffset:CGPointMake(0, diff+_self.myTableView.contentOffset.y)];
    };
    NSMutableArray *menuItemArray = [[NSMutableArray alloc] init];
    BOOL hasTaxtToCopy = (curMsg.Talk && ![curMsg.Talk isEmpty]);
    BOOL canDelete = (curMsg.sendStatus != PrivateMessageStatusSending);
    
    [menuItemArray addObject:@"拷贝"];
    
    if (canDelete) {
        [menuItemArray addObject:@"删除"];
    }
    
    
    [cell.bgImgView addLongPressMenu:menuItemArray clickBlock:^(NSInteger index, NSString *title) {
        ESStrongSelf;
        if ([title hasPrefix:@"拷贝"]) {
            [[UIPasteboard generalPasteboard] setString:curMsg.Talk];
        }else if ([title isEqualToString:@"删除"]){
            [_self showAlertToDeleteMessage:curMsg];
        }
    }];
    
    
    
    
    return cell;
}

- (void)showAlertToDeleteMessage:(PrivateMessage *)toDeleteMsg{
    self.messageToResendOrDelete = toDeleteMsg;
    [self.myMsgInputView isAndResignFirstResponder];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"删除后将不会出现在你的私信记录中" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确认删除" otherButtonTitles:nil];
    actionSheet.tag = kTagActionDeleteMessage;
    [actionSheet showInView:kKeyWindow];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PrivateMessage *preMessage = nil;
    NSUInteger curIndex = ([_myPriMsgs.list count] -1) - indexPath.row;
    if (curIndex +1 < _myPriMsgs.list.count) {
        preMessage = [_myPriMsgs.list objectAtIndex:curIndex+1];
    }
    return [MessageCell cellHeightWithObj:[_myPriMsgs.list objectAtIndex:curIndex] preObj:preMessage];
}

- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [self.myTableView numberOfRowsInSection:0];
    if(rows > 0) {
        [self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
                                atScrollPosition:UITableViewScrollPositionBottom
                                        animated:animated];
    }
}

//- (UIView *)msgInputView{
//    UIView *msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 44)];
//    msgInputView.backgroundColor = [UIColor redColor];
//
//    UITextView *inputView = [[UITextView alloc]initWithFrame:CGRectMake(15, 7, kScreen_Width-15*2-65, 30)];
//    inputView.font = [UIFont systemFontOfSize:15];
//    inputView.returnKeyType = UIReturnKeySend;
//    inputView.scrollsToTop = NO;
//    inputView.delegate = self;
//
//    [msgInputView addSubview:inputView];
//    return msgInputView;
//}

#pragma mark UIMessageInputView M

- (void)sendPrivateMessage:(id)obj{
    PrivateMessage *nextMsg = [PrivateMessage privateMessageWithObj:obj andSender:me andusername:_myOrder.Username];
    [self sendPrivateMessageWithMsg:nextMsg];
}

- (void)sendPrivateMessageWithMsg:(PrivateMessage *)nextMsg{
    NSLog(@"sendmeg");
    [_myPriMsgs sendNewMessage:nextMsg];
    [self.myTableView reloadData];
    [self scrollToBottomAnimated:YES];
    
    __weak typeof(self) weakSelf = self;
    
    //发送消息
    [[NetBaiduManager sharedManager]push_PrivateMessage:(PrivateMessage*)nextMsg andOrder:(Order*)_myOrder andBlock:^(id data, NSError *error) {
        if (data) {
            //发送成功
            NSLog(@"发送成功");
            [weakSelf.myPriMsgs sendSuccessMessage:nextMsg andOldMessage:nextMsg];
        }
        [weakSelf.myTableView reloadData];
        [self saveToArchiver];
        [weakSelf scrollToBottomAnimated:YES];
    }];
    
}
- (void)deletePrivateMessageWithMsg:(PrivateMessage *)curMsg{
    if (curMsg.sendStatus == PrivateMessageStatusSendFail) {
        [_myPriMsgs deleteMessage:curMsg];
        [self saveToArchiver];
        [_myTableView reloadData];
    }else if (curMsg.sendStatus == PrivateMessageStatusSendSucess) {
        [_myPriMsgs deleteMessage:curMsg];
        [self saveToArchiver];
        [_myTableView reloadData];
    }
}


#pragma mark UIActionSheetDelegate M
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == kTagActionResendMessage){
        if (buttonIndex == 0) {
            if (_messageToResendOrDelete) {
                [self sendPrivateMessageWithMsg:_messageToResendOrDelete];
            }
        }
    }else if (actionSheet.tag == kTagActionDeleteMessage){
        if (buttonIndex == 0) {
            if (_messageToResendOrDelete) {
                [self deletePrivateMessageWithMsg:_messageToResendOrDelete];
            }
        }
    }
}




#pragma mark ScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _myTableView) {
        [_myMsgInputView isAndResignFirstResponder];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentSize.height >CGRectGetHeight(scrollView.bounds)
        && scrollView.contentOffset.y < 5) {
        _preContentHeight = self.myTableView.contentSize.height;
        DebugLog(@"加载更多");
    }
}

- (void)dealloc
{
    _myTableView.delegate = nil;
    _myTableView.dataSource = nil;
}

@end
